<template>
  <div class="container">
    <!-- 固定导航 -->
    <van-nav-bar
      fixed
      left-arrow
      @click-left="$router.go(-1)"
      title="小思同学"
      />

    <!-- 聊天主体区域 -->
    <div class="chat-list">
      <div
        v-for="(obj, idx) in chatList"
        :key="idx">
          <!-- 左侧是机器人小思 -->
          <div
            ref="chat-item"
            class="chat-item left"
            v-if="obj.name === 'xs'">
            <van-image fit="cover" round src="https://img.yzcdn.cn/vant/cat.jpeg" />
            <div class="chat-pao">{{ obj.msg }}</div>
          </div>

          <!-- 右侧是当前用户 -->
          <div
            ref="chat-item"
            class="chat-item right"
            v-if="obj.name === 'me'">
            <div class="chat-pao">{{ obj.msg }}</div>
            <van-image
              fit="cover"
              round
              :src="userInfo.photo" />
          </div>
       </div>
    </div>

    <!-- 对话区域 -->
    <div class="reply-container van-hairline--top" style="display:flex;">
      <van-field
        v-jujiao
        v-model.trim="txt"
        placeholder="说点什么..."
        @keydown.enter="sendMsgFn"
        />
      <van-button
        @click="sendMsgFn"
        style="width:80px;font-size:14px;"
        >发送</van-button>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { io } from 'socket.io-client'
import { Notify } from 'vant'
let socket = null
export default {
  name: 'Chat',
  data () {
    return {
      txt: '', // 输入框的内容
      // 聊天列表
      chatList: JSON.parse(window.localStorage.getItem('chatList')) || [
        // 只根据 name 属性，即可判断出这个消息应该渲染到左侧还是右侧
        {
          name: 'xs', msg: 'Can I help you?'
        }
      ]
    }
  },
  computed: {
    ...mapState(['userInfo'])
  },
  created () {
    // 1. 连接服务器
    socket = io('ws://toutiao.itheima.net', {
      query: {
        token: this.$store.state.token
      },
      transports: ['websocket']
    })
    // 2. 监听连接成功事件
    socket.on('connect', () => {
      // 4. 接收（来自服务器的消息）
      socket.on('message', data => {
        // data 就是 小思 回应 的 消息
        // this.chatList.push({
        //   name: 'xs',
        //   msg: data.msg
        // })
        this.chatList.push({
          ...data,
          name: 'xs'
        })
        // 异步更新
        this.$nextTick(() => {
          this.scrollIntoView()
        })
      })
    })
  },
  watch: {
    chatList (newVal) {
      window.localStorage.setItem('chatList', JSON.stringify(newVal))
    }
  },
  methods: {
    // 让最后一个 chat-item 滚动到 视口范围内
    scrollIntoView () {
      // 获取所有的 chat-item dom元素
      const chatItems = this.$refs['chat-item']
      // 找到最后一个
      const chatItem = chatItems[chatItems.length - 1]
      // 让最后一个chat-item 滚动到视口
      chatItem.scrollIntoView({
        behavior: 'smooth'
      })
    },
    // 发送消息
    sendMsgFn () {
      if (!this.txt) {
        Notify({ type: 'warning', message: '消息内容不能为空' })
        return
      }
      // 3. 发送消息
      socket.emit('message', {
        msg: this.txt,
        timestamp: Date.now()
      })

      this.chatList.push({
        name: 'me',
        msg: this.txt
      })
      // 异步更新
      this.$nextTick(() => {
        this.scrollIntoView()
      })
      this.txt = ''
    }
  },
  destroyed () {
    // if (socket) {
    //   socket.close()
    // }
    socket && socket.close()
  }
}
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  box-sizing: border-box;
  background: #fafafa;
  padding: 46px 0 50px 0;
  .chat-list {
    height: 100%;
    overflow-y: scroll;
    .chat-item {
      padding: 10px;
      .van-image {
        vertical-align: top;
        width: 40px;
        height: 40px;
      }
      .chat-pao {
        vertical-align: top;
        display: inline-block;
        min-width: 40px;
        max-width: 70%;
        min-height: 40px;
        line-height: 38px;
        border: 0.5px solid #c2d9ea;
        border-radius: 4px;
        position: relative;
        padding: 0 10px;
        background-color: #e0effb;
        word-break: break-all;
        font-size: 14px;
        color: #333;
        &::before {
          content: '';
          width: 10px;
          height: 10px;
          position: absolute;
          top: 12px;
          border-top: 0.5px solid #c2d9ea;
          border-right: 0.5px solid #c2d9ea;
          background: #e0effb;
        }
      }
    }
  }
}
.chat-item.right {
  text-align: right;
  .chat-pao {
    margin-left: 0;
    margin-right: 15px;
    &::before {
      right: -6px;
      transform: rotate(45deg);
    }
  }
}
.chat-item.left {
  text-align: left;
  .chat-pao {
    margin-left: 15px;
    margin-right: 0;
    &::before {
      left: -5px;
      transform: rotate(-135deg);
    }
  }
}
.reply-container {
  position: fixed;
  left: 0;
  bottom: 0;
  height: 44px;
  width: 100%;
  background: #f5f5f5;
  z-index: 9999;
}
</style>
